package com.example.librarymanagementsystem.interceptor;

import com.example.librarymanagementsystem.constant.Constants;
import com.example.librarymanagementsystem.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
//拦截器
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求处理前执行的逻辑，类似于安保查证件   true表示放行，不进行拦截      false表示拦截，不进行下一步处理
        log.info("LoginInterceptor preHandle");
        //获取session，并且判断session中存储的userinfo信息是否为空
        HttpSession session = request.getSession();//如果有则返回，没有也不生成
        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USER_SESSION_KEY);
        if(userInfo==null||userInfo.getId()<=0){
            //用户未登录
            response.setStatus(401);
            return false;
        }
        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        //请求处理后执行的逻辑
//        log.info("LoginInterceptor postHandle");
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        //视图渲染后执行的逻辑
//        log.info("LoginInterceptor afterCompletion");
//    }
}
